package com.liu.stockmarket.repository.database.converter

import androidx.room.TypeConverter
import com.liu.stockmarket.model.Stock
import com.liu.stockmarket.repository.database.entity.TransactionRecordEntity
import java.math.BigDecimal
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

/**
 * Room 的类型转换
 */
object Converters {
    @TypeConverter
    fun bigDecimalToString(b: BigDecimal?): String? {
        if (b == null) {
            return null
        }
        return b.toString()
    }

    @TypeConverter
    fun stringToBigDecimal(s: String?): BigDecimal? = if (s == null) null else BigDecimal(s)

    @TypeConverter
    fun localDateTimeToString(localDateTime: LocalDateTime): String =
        DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(localDateTime)


    @TypeConverter
    fun stringToLocalDateTime(s: String): LocalDateTime =
        LocalDateTime.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))


    @TypeConverter
    fun localDateToString(localDate: LocalDate?): String? =
        if (localDate == null) null else DateTimeFormatter.ofPattern("yyyy-MM-dd").format(localDate)


    @TypeConverter
    fun stringToLocalDate(s: String?): LocalDate? =
        if (s == null) null else LocalDate.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd"))

    @TypeConverter
    fun toStockType(index: Int): Stock.StockType {
        return Stock.StockType.values()[index]
    }

    @TypeConverter
    fun formStockType(stockType: Stock.StockType): Int {
        return stockType.ordinal
    }

    @TypeConverter
    fun toTransactionType(index: Int): TransactionRecordEntity.TransactionType {
        return TransactionRecordEntity.TransactionType.values()[index]
    }

    @TypeConverter
    fun formTransactionType(type: TransactionRecordEntity.TransactionType): Int {
        return type.ordinal
    }

    @TypeConverter
    fun toTransactionExchange(index: Int): Stock.TransactionExchange {
        return Stock.TransactionExchange.values()[index]
    }

    @TypeConverter
    fun formTransactionExchange(type: Stock.TransactionExchange): Int {
        return type.ordinal
    }



}